package com.example.ios_del1.myapplicationtest;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.media.Image;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import com.android.volley.toolbox.Volley;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import jakewharton.disklrucache.OkHttpClientManager2;


public class MainActivity extends AppCompatActivity {

    private TextView tv;
    private ImageView im;

    private String IMGIP = "https://www.baidu.com/img/bd_logo1.png";
    private Cache cache;
    RequestQueue mQueue ;

    ImageLoader imageLoader;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activitym);
//        tv = (TextView) this.findViewById(R.id.tv);
//        im = (ImageView) this.findViewById(R.id.show_img);
        cache = new Cache(MainActivity.this);

        mQueue= Volley.newRequestQueue(getApplicationContext());
        imageLoader = new ImageLoader(mQueue, new ImageLoader.ImageCache() {
            @Override
            public void putBitmap(String url, Bitmap bitmap) {
            }

            @Override
            public Bitmap getBitmap(String url) {
                return null;
            }
        });
        MyAdapter adapter=new MyAdapter();
        ListView listView= (ListView) findViewById(R.id.listview);
        listView.setAdapter(adapter);
        listView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {

            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

            }
        });
    }


    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.getImg:
                cacheImg();
                break;
            case R.id.showImgbtn:
                showImg();
                break;
            case R.id.clearCache:
                clearCache();
                break;
            case R.id.getSize:
                getCacheSize();
                break;
            case R.id.deleteAll:
                deleteAll();
                break;
            default:
                break;
        }
    }

    private void deleteAll() {
        /**
         * ’‚∏ˆ∑Ω∑®”√”⁄Ω´À˘”–µƒª∫¥Ê ˝æ›»´≤ø…æ≥˝£¨±»»ÁÀµÕ¯“◊–¬Œ≈÷–µƒƒ«∏ˆ ÷∂Ø«Â¿Ìª∫¥Êπ¶ƒ‹£¨
         * ∆‰ µ÷ª–Ë“™µ˜”√“ªœ¬DiskLruCacheµƒdelete()∑Ω∑®æÕø…“‘ µœ÷¡À°£
         * ª·…æ≥˝∞¸¿®»’÷æŒƒº˛‘⁄ƒ⁄µƒÀ˘”–Œƒº˛
         */
        cache.delete();

    }

    private void getCacheSize() {
        tv.setText(cache.size() + "");
    }

    public String hashKeyForDisk(String key) {
        String cacheKey;
        try {
            final MessageDigest mDigest = MessageDigest.getInstance("MD5");
            mDigest.update(key.getBytes());
            cacheKey = bytesToHexString(mDigest.digest());
        } catch (NoSuchAlgorithmException e) {
            cacheKey = String.valueOf(key.hashCode());
        }
        return cacheKey;
    }

    private String bytesToHexString(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(0xFF & bytes[i]);
            if (hex.length() == 1) {
                sb.append('0');
            }
            sb.append(hex);
        }

        return sb.toString();
    }


    private void clearCache() {
        cache.remove(IMGIP);

    }

    private void showImg() {
//        String key =hashKeyForDisk(IMGIP);
//        try {
//            DiskLruCache.Snapshot snapShot = mDiskLruCache.get(key);
//
//            if(snapShot!=null){
//                InputStream is = snapShot.getInputStream(0);
//                Bitmap bitmap = BitmapFactory.decodeStream(is);
//                im.setImageBitmap(bitmap);
//            }else{
//                Log.e("Tag","@ASDFASDF");
//
//                im.setImageBitmap(null);
//            }
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
        ImageCacheUtils imageCacheUtils= new ImageCacheUtils(this,handler);
        imageCacheUtils.getImageBitmap(IMGIP,1);
//        cache.test(im, IMGIP);
    }
     private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Bitmap bitmap= (Bitmap) msg.obj;
            im.setImageBitmap(bitmap);

        }
    };

    private void cacheImg() {
        cache.test(im, IMGIP);
    }

    @Override
    protected void onPause() {
        super.onPause();
        cache.flush();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();

        cache.close();

    }


    class MyAdapter extends BaseAdapter{
        private Holder holder;
        @Override
        public int getCount() {
            return Images.imageUrls.length;
        }

        @Override
        public Object getItem(int position) {
            return Images.imageUrls[position];
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

//            ViewHolder holder = null;
//            if (convertView == null) {
//                holder = new ViewHolder();
//                convertView = View.inflate(getActivity(), R.layout.freeze_dialog_layout_item, null);
//                holder.title = (TextView) convertView.findViewById(R.id.freeze_car_number);
//                convertView.setTag(holder);
//            } else {
//                holder = (ViewHolder) convertView.getTag();
//            }
//


            if (convertView == null) {
                convertView=new NetworkImageView(MainActivity.this);
                holder=new Holder();
                holder.imageView= (NetworkImageView) convertView;
                convertView.setTag(holder);
            }else {
                holder= (Holder) convertView.getTag();
            }
//            networkImageView.setDefaultImageResId(R.drawable.default_image);
//            networkImageView.setErrorImageResId(R.drawable.failed_image);

           holder.imageView.setImageUrl(Images.imageUrls[position],imageLoader);
//            OkHttpClientManager2.getDisplayImageDelegate().displayImage(holder.imageView,Images.imageUrls[position]);
//            cache.test(holder.imageView, Images.imageUrls[position]);
//            holder.imageView.setBackgroundColor(Color.RED);

            return convertView;
        }
    }

    class Holder{
        NetworkImageView imageView;
    }


}
